﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.WindowsAzure.ServiceRuntime;
using System.Net;

namespace WebRole1
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ListBox1.Items.Clear();
        }

        /// <summary>
        /// Event button, call to WCF Worker roles
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                // Read all Worker roles instances
                foreach (RoleInstance instance in RoleEnvironment.Roles["WorkerRole1"].Instances)
                {
                    try
                    {
                        // Retrieve the Worker role URL
                        IPEndPoint ipEndPoint = instance.InstanceEndpoints["HelloService"].IPEndpoint;
                        HelloService.HelloProxy proxy = new HelloService.HelloProxy();

                        // retirve a WCF instance
                        HelloService.IHellloService service = proxy.GetAProxy(HelloService.HelloProxy.GetUrlFormat(ipEndPoint));

                        // Call to WCF method
                        string roleName = service.RoleName();
                        ListBox1.Items.Add(roleName);
                    }
                    catch(Exception exConnection)
                    {
                        ListBox1.Items.Add(string.Format("Exception {0}: {1}", instance.Id, exConnection.Message));
                    }
                }
            }
            catch (Exception ex)
            {
                LabelError.Text = ex.Message;
            }
        }
    }
}